package ballena.activities;

import ballena.activities.R;
import ballena.utiles.Global;
import ballena.utiles.Servlet;
import android.app.Activity;
import android.content.Intent;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Looper;
import android.os.Vibrator;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class Principal extends Activity implements Runnable {
	private GridView grdPrincipal;
	private String[] gridOpciones = new String[]{"Noticias","Muro","Mensajes","Fotos","Amigos","Localiza","Buscar","Extras","Salir"};
	@SuppressWarnings("unused")
	private ProgressDialog pd;
    public int contMensaje=0;
	public LocationManager mLocationManager;
	public Location mLocation;
	public MyLocationListener mLocationListener;
	public int contador=0;
	
	

	public Location currentLocation = null;
	
    public Location getCurrentLocation() {
		return currentLocation;
	}
    

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.principal);
		grdPrincipal = (GridView) findViewById(R.id.gridPrincipal);
		iniciarVista();
		writeSignalGPS();
	}
	
	public void onDestroy(){
		super.onDestroy();
		mLocationManager.removeUpdates(mLocationListener);
		desconectar();
	}
	

	public void setCurrentLocation(Location loc) {
    	currentLocation = loc;
    }
    
    
    public void writeSignalGPS() {
    	
    	@SuppressWarnings("unused")
		DialogInterface.OnCancelListener dialogCancel = new DialogInterface.OnCancelListener() {

            public void onCancel(DialogInterface dialog) {
                Toast.makeText(getBaseContext(), 
                        getResources().getString(R.string.gps_signal_not_found), 
                        Toast.LENGTH_LONG).show();
                contador=0;
            }
          
        };
    	
		Thread thread = new Thread(this);
		thread.start();

    }

	@Override
	public void run() {
    	
		mLocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
		
		if (mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
			
			Looper.prepare();
			
			mLocationListener = new MyLocationListener();
			
			mLocationManager.requestLocationUpdates(
	                LocationManager.GPS_PROVIDER, 0, 0, mLocationListener);
			Looper.loop(); 
			Looper.myLooper().quit(); 
			
		} else {
			
            Toast.makeText(getBaseContext(), 
                    getResources().getString(R.string.gps_signal_not_found), 
                    Toast.LENGTH_LONG).show();
            contador=0;
            
		}
	}
    
	
	
	public void servletEnviarLocalizacionUsuario (int latitud, int longitud) {
		
			String param[] = { "usuario=" + Global.usuario.getId(), "latitud=" + latitud, "longitud=" + longitud};
					
			Servlet s = new Servlet(Global.SERVLETENVIALOC, param);
			
			s.conectar();
	}
	
    public class MyLocationListener implements LocationListener 
    {
        @Override
        public void onLocationChanged(Location loc) {
            
                if (contador==0){
                	Toast.makeText(getBaseContext(), 
                			getResources().getString(R.string.gps_signal_found), 
                            Toast.LENGTH_LONG).show();
                	contador++;
                }
                if (loc==null){
                	Toast.makeText(getApplicationContext(), 
                			"Conexion perdida", Toast.LENGTH_LONG).show();
                	contador=0;
                }
                    
                setCurrentLocation(loc);
                int latitud=(int) (loc.getLatitude()*1E6);
                int longitud=(int) (loc.getLongitude()*1E6);
                servletEnviarLocalizacionUsuario(latitud, longitud);
                //Log.i("---------lat",""+loc.getLatitude());    
        }

        @Override
        public void onProviderDisabled(String provider) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onProviderEnabled(String provider) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onStatusChanged(String provider, int status, 
            Bundle extras) {
            // TODO Auto-generated method stub
        }
        
    } 
    

	
	static class ViewHolder {
		ImageView botonGrid;
		TextView tvPrincipal;
	}

	private void refreshListItems() {
		AdaptadorBotones adaptador = new AdaptadorBotones(this);
		grdPrincipal.setAdapter(adaptador);
	}
	

	private void iniciarVista() {
		refreshListItems();
	}

	
	@SuppressWarnings("rawtypes")
	class AdaptadorBotones extends ArrayAdapter {
		Activity context;

		@SuppressWarnings("unchecked")
		AdaptadorBotones(Activity context) {
			super(context, R.layout.item_principal, gridOpciones);
			this.context = context;
		}


		public View getView(final int position, View convertView,
				ViewGroup parent) {

			View item = convertView;
			ViewHolder holder;
			if (item == null) {
				LayoutInflater inflater = context.getLayoutInflater();
				item = inflater.inflate(R.layout.item_principal, null);
				holder = new ViewHolder();

				holder.botonGrid = (ImageView) item
						.findViewById(R.id.imgBtnPrincipal);
				holder.tvPrincipal = (TextView) item
						.findViewById(R.id.tvPrincipal);

				item.setTag(holder);
			} else {
				holder = (ViewHolder) item.getTag();
			}
			int resID;
			resID = getResources().getIdentifier(
					gridOpciones[position].toLowerCase(), "drawable",
					getPackageName());
			holder.botonGrid.setImageResource(resID);
			holder.tvPrincipal.setText(gridOpciones[position]);


			holder.botonGrid.setOnClickListener(new View.OnClickListener() {
				public void onClick(View view) {
					Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
					vibrator.vibrate(500);
					dirigirmeA(position);
				}
			});
			return item;
		}
	}

	void dirigirmeA(int opcion) {
		/*
		 * "Noticias", "Muro", "Mensaje", "Fotos", "Amigos", "Localiza",
		 * "Buscar", "Extras","Salir"
		 */
		Intent intent = new Intent();
		switch (opcion) {
		case 0: //"Noticias"
			Intent intentNoticias = new Intent(Principal.this, Noticias.class);
			startActivity(intentNoticias);
			break;
		case 1: //"Perfil" 
			Intent intentPerfil = new Intent(Principal.this, Perfil.class);
			Bundle bundlePerfil = new Bundle();
			bundlePerfil.putInt("ID", Global.usuario.getId());
			bundlePerfil.putString("NOMBRE", Global.usuario.getNombre());
			intentPerfil.putExtras(bundlePerfil);
			startActivity(intentPerfil);
			break;
		case 2: // "Mensaje"
			intent = new Intent(Principal.this, Mensajes.class);
			Bundle bundle = new Bundle();
			bundle.putString("OPCION", Global.MENSAJES_RECIBIDOS);
			intent.putExtras(bundle);
			startActivity(intent);
			break;
		case 3:
			Intent aImagenes = new Intent(Principal.this, Imagenes.class);
			startActivity(aImagenes);
			break;
		case 4: // "Amigos"
			intent = new Intent(Principal.this, Amigos.class);
			startActivity(intent);
			break;
		case 5:
			intent = new Intent(Principal.this, Geolocalizacion.class);
			startActivity(intent);
			break;
		case 6:
			intent = new Intent(Principal.this, Buscar.class);
			startActivity(intent);
			break;
		case 7: // "Extras"
			intent = new Intent(Principal.this, AmigosOnline.class);
			startActivity(intent);
			break;
		case 8:
			finish();
			//onDestroy();

			break;
		
		default:
			refreshListItems();
		}
	}	
	public void desconectar (){
		String param[] = { "usuario=" + Global.usuario.getId(), "accion=" + Global.DESCONECTAR};
		Servlet s = new Servlet(Global.SERVLET, param);
		s.conectar();
	}

}